import { mapGetters } from 'vuex';
import { alertHtmlWithCallback, alertMessage, isValidateNull, showAlertMessage } from '@/utils/utils';
import { getRoleDetailApi, createOrEditRoleApi } from './create-role.service';
export default {
  name: 'create-role',
  components: {},
  directives: {},
  props: {
    roleId: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      loading: false, // table loading
      showDialog: true, // 是否显示弹窗
      title: '创建职位',
      editForm: {}, // 编辑用户表单
      editRules: {
        name: [{ required: true, trigger: "change", validator: isValidateNull }]
      } // 编辑表单验证规则
    }
  },
  computed: {
    ...mapGetters([
      'codesCheck'
    ])
  },
  created() {
    if (this.roleId) {
      this.title = '编辑职位';
      this.getRoleDetail();
    }
  },
  methods: {
    // 获取详情
    getRoleDetail() {
      getRoleDetailApi(this.roleId).then(res => {
        this.editForm = res.data;
      })
    },

    // 创建或者编辑信息
    save() {
      // 表单验证
      this.$refs.dataForm.validate(valid => {
        if (valid) {
          const message = {
            name: this.editForm.name,
            description: this.editForm.description
          }
          const alertMsg = showAlertMessage(`请确认${!this.editForm.objectId ? '创建' : '编辑'}内容`, message)
          alertHtmlWithCallback(alertMsg, `确认要${!this.editForm.objectId ? '创建' : '编辑'}这条信息吗?`).then(yes => {
            if (yes) {
              createOrEditRoleApi(this.editForm).then((res) => {
                alertMessage(res.message);
                this.showDialog = false;
                this.$emit('reload', true)
              }).catch(() => { }); // 关闭confirm框的回调，不处理的话会报一个js error
            }
          })
        }
      });
    },

    // 关闭dialog时需要告诉父组件隐藏弹窗
    closeDialog() {
      this.showDialog = false;
      this.$emit('close', true);
    }
  }
}
